<?php
namespace app\index\controller;

use app\index\model\CompanyModel;
use app\index\model\LoginTokenModel;
use app\index\model\UserModel;
use app\index\service\LoginService;
use think\App;
use think\Db;
class Common extends Access
{
    protected $userinfo;
    protected $cominfo;
    /**
     * Common constructor.
     * @param App|null $app
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->check_login();
        $this->create_opt_dt();
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
   private function check_login(){
       $token = getDecryptToken(str_replace('&&++&&','/', $this->request->param('token','','string')));
       if(!$token) $this->to_login_fail();

       $tokenInfo = LoginTokenModel::where(['token'=>$token])->where('enddt', 'gt', date('Y-m-d H:i:s'))->find();
       if(!$tokenInfo) $this->to_login_fail();

       $userinfo = UserModel::get_info_by_pk($tokenInfo['uid']);
       if(!$userinfo || $userinfo['status'] != 1 || $userinfo['deleted_user'] > 0) $this->to_login_fail();

       $cominfo = CompanyModel::get_info_by_pk($userinfo['comid']);
       if(!$cominfo || $cominfo['status'] != 1) $this->to_login_fail();
       if(!empty($cominfo['enddt']) && $cominfo['enddt'] != '0000-00-00'){
           if($cominfo['enddt'] < date('Y-m-d')) $this->to_login_fail();
       }

       if(!(new LoginService())->user_more_dept_disable($userinfo['deptid']))  $this->to_login_fail();

       if($userinfo['isreg'] == 1 && $userinfo['reg_enddt'] < date('Y-m-d H:i:s')){
           $this->to_login_fail();
       }


       if($cominfo['issingle'] != 1){
           $last_token = LoginTokenModel::where(['uid'=>$userinfo['id']])->order('id DESC')->limit(1)->select()->toArray();
           if($last_token[0]['token'] != $token) $this->to_login_fail();
       }

       $userinfo['token_roletype'] = $tokenInfo['roletype'];
       $userinfo['token_id'] = $tokenInfo['id'];
       $userinfo['token_ktype'] = $tokenInfo['ktype'];
       $this->userinfo = $userinfo;
       $this->cominfo = $cominfo;
   }

   private function create_opt_dt(){
       return UserModel::where(['id'=>$this->userinfo['id']])->update(['lastoptdt'=>date('Y-m-d H:i:s')]);
   }

   protected function to_login_fail(){
       json(['code' => 4500, 'message' => lang('code_4500')])->send();exit();
   }

}























